# -*- encoding: utf-8 -*-
'''
@File    :   log_split.py
@Time    :   2023/08/02
@Author  :   Han Xiao
@Brief   :   根据提供的时间点分割LOG文件
'''
import argparse
import datetime

parser = argparse.ArgumentParser()
parser.add_argument('-l','--log', help="LOG 文件路径，使用绝对路径")
parser.add_argument('-d','--day', help="日期，务必确认，格式 MMDD")
parser.add_argument('-ts','--time_start',help="开始时间 格式 hhmmss")
parser.add_argument('-te','--time_end',help="结束时间 格式 hhmmmss")
parser.add_argument('-f','--format', default=1, help='默认为1表示原智耘log格式, 2表示新智耘格式' )
# HXG TODO 开始时间+持续时间
args = parser.parse_args()

log_format = int(args.format)

if args.log:
    log_path = args.log
else:
    parser.print_help()
    exit()

if args.day and len(args.day) == 4:
    day = args.day
else:
    parser.print_help()
    exit()

if args.time_start and len(args.time_start) == 6:
    start_hour = args.time_start[:2]
    start_min = args.time_start[2:4]
    start_sec = args.time_start[4:]
else:
    parser.print_help()
    exit()

if args.time_end and len(args.time_end) == 6:
    end_hour = args.time_end[:2]
    end_min = args.time_end[2:4]
    end_sec = args.time_end[4:]
else:
    parser.print_help()
    exit()

s_time = start_hour + ":" + start_min + ":" + start_sec
e_time = end_hour + ":" + end_min + ":" + end_sec

# print(e_time)

out_put_log = day + "_" + args.time_start + "_" + args.time_end + ".log"


with open(log_path, 'r') as f:
    lines = f.readlines()

s_day = "I" + day # LOG 默认INFO级别
if log_format == 2:
    if len(day) == 4:
        part1, part2 = day[:2], day[2:]
        s_day = f"{datetime.datetime.now().year}-{part1}-{part2}"

for i, line in enumerate(lines):
    if s_time in line and s_day in line:
        print(f'The first occurrence of "{s_time}" is in line {i + 1}')
        start_index = i + 1
        break
    if i == len(lines) - 1:
        print("没找到开始时间")
        start_index = -1
    
for i in range(len(lines) - 1, -1, -1):
    if e_time in lines[i] and s_day in lines[i]:
        print(f'The last occurrence of "{e_time}" is in line {i + 1}')
        end_index = i + 1
        break
    if i == 0:
        print("没找到结束时间")
        end_index = -1


if start_index == -1 or end_index == -1:
    print("时间不对")
    exit()

if start_index > end_index:
    print("时间反了")
    t = start_index
    start_index = end_index
    end_index = t
    # exit()

middle_content = ''.join(lines[start_index-1:end_index-1])

with open(out_put_log, 'w') as f:
    f.write(middle_content)

